package com.more.offer.threadtest.futureTaskTest;

import java.util.Comparator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author yinpeng10
 * @desc
 */
public class ComletableFutureTest {

	public static void main(String[] args) throws ExecutionException, InterruptedException {

//		CompletableFuture<String> completableFuture=new CompletableFuture<>();
//		Runnable runnable  = () -> {
//			try {
//				System.out.println(Thread.currentThread().getName() + " 执行中");
//				Thread.sleep(3000);
//				completableFuture.complete("success..");
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//		};
//
//		Thread thread = new Thread(runnable);
//		thread.start();
//		try {
//			String result = completableFuture.get();
//			System.out.println("Thread: " + Thread.currentThread().getName() + " " + result);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		} catch (ExecutionException e) {
//			e.printStackTrace();
//		}
//
//		CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//			System.out.println(Thread.currentThread().getName() + " 正在执行一个没有返回值的异步任务");
//			try {
//				Thread.sleep(3000);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//		});
//		future.get();
//		System.out.println("结束");

		ExecutorService executorService = Executors.newFixedThreadPool(4);
		CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
			System.out.println("hello world");
		}, executorService);
		CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
			System.out.println("hello world");
			String result = "result";
			return result;
		}).whenComplete((r,e) -> {
			System.out.println( "complete " + r + " " + e);
		}).exceptionally( (e) -> {
			System.out.println("excep: " + e);
			return "exception";
		});

		System.out.println(future.get());
		System.out.println(completableFuture.get());

		CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> {
			System.out.println("hello world");
			return "result";
		});
		CompletableFuture<Integer> f2 = f1.handle((r, e) -> {
			System.out.println("handle: " + r);
			return 1;
		});
	}
}
